package com.ukefu.util.ai;

import java.io.IOException;

import org.apache.commons.lang.ArrayUtils;
import org.lionsoul.jcseg.tokenizer.core.JcsegException;

public class AiDic {
	
	private final AiDicTrie trie ;
	
	private Node[] dic = new Node[1];
	
	class Node {
		int code;
		int depth;
		int id ;
		AiDic aiDic ;
		public String toString(){
			return aiDic.trie.getDicMap().inverse().get(code) ;
		}
	};
	
	public AiDic(AiDicTrie trie){
		this.trie = trie ;
	}
	
	private Node[] resize() {
		Node[] base = new Node[dic.length * 2];
		System.arraycopy(dic, 0, base, 0, dic.length);
		dic = base;
		return dic;
	}
	public Node search(String content) throws IOException, JcsegException{
		return search(DicSegment.segment(content)) ;
	}
	
	private Node search(String[] content){
		if (ArrayUtils.isEmpty(content)){
			return null ;
		}
		Node[] temp = dic ;
		Node result =null  ;
		for(int i=0 ; i< content.length ; i++){
			String word = content[i] ;
			int code = trie.getWordInx(word) ;
			int inx = fetch(temp,code , false) ;
			if(inx < temp.length && temp[inx] != null){
				result = temp[inx] ;
			}
			if(inx >= temp.length){
				result = null ; break ;
			}
			if(temp[inx]!=null && temp[inx].aiDic!=null){
				temp = temp[inx].aiDic.dic ;
			}
		}
		return result ;
	}
	
	private int fetch(Node[] dicDept , int code , boolean fixed){
		int dicInx = -1 ;
		for(int i=0 ; i<dicDept.length ; i++){
			Node node = dicDept[dicInx = i] ;
			if(node!=null){
				if(code == node.code){
					dicInx = i ;
				}else{
					continue ;
				}
			}
			break ;
		}
		if(dicInx>=0 && dicDept[dicInx]!=null && (dicInx+1) == dicDept.length && fixed){
			dicInx = dicInx+1 ;
		}
		return dicInx ;
	}
	
	public void insert(String content , int id) throws IOException, JcsegException{
		insert(DicSegment.segment(content) , id);
	}
	
	private void insert(String[] content , int id) {
		if (ArrayUtils.isEmpty(content)){
			return ;
		}
		Node[] temp = dic ;
		for(int i=0 ; i< content.length ; i++){
			String word = content[i] ;
			int code = trie.getWordInx(word) ;
			int inx = fetch(temp,code , true) ;
			if (inx >= temp.length){
				temp = resize();
			}
			if(inx >= dic.length || temp[inx] == null){	//未在字典里出现，增加内容
				temp[inx] = new Node();
				temp[inx].code = code ;
				temp[inx].depth = i ;
				temp[inx].aiDic = new AiDic(trie) ;
				if(i == (content.length -1)){
					temp[inx].id = id ;
				}
			}
			temp = temp[inx].aiDic.dic ;
		}
	}
}
